package com.ytoglobal.overseas.address.platform.common.configuration;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Auther: zxl
 * @Date: 2018/10/26 15:15
 * @Description:
 */
@Configuration
@Slf4j
@ConditionalOnProperty(value = "elasticsearch.enabled", havingValue = "true")
public class ElasticsearchConfig {

    @Value("${elasticsearch.host}")
    private String hostName;

    @Value("${elasticsearch.port}")
    private Integer port;

    @Value("${elasticsearch.max-conn}")
    private Integer maxConn;

    @Value("${elasticsearch.max-per-route-conn}")
    private Integer maxPerRouteConn;

    @Value("${elasticsearch.xpack.user}")
    private String xpackUser;

    @Value("${elasticsearch.xpack.password}")
    private String xpackPassword;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        String[] hostStrs = hostName.split(",");
        HttpHost[] httpHosts = new HttpHost[hostStrs.length];
        for (int i = 0; i < hostStrs.length; i++) {
            String host = hostStrs[i];
            httpHosts[i] = new HttpHost(host, port, "http");
        }
        RestClientBuilder restClientBuilder = RestClient.builder(httpHosts);
        /** 用户认证对象 */
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        /** 设置账号密码 */
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(xpackUser, xpackPassword));
        restClientBuilder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setMaxConnTotal(maxConn);
            httpClientBuilder.setMaxConnPerRoute(maxPerRouteConn);
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            return httpClientBuilder;
        });

        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClientBuilder);
        return restHighLevelClient;
    }
}
